import rp = require("request")
import { EnhancedConnection } from "./storage/MySqlStore"

export interface IndexField {
    order: string
    field: string
}

export interface MongoIndex {
    name: string
    fields: IndexField[]
    unique?: boolean
    sparse?: boolean
    errorMessage: string
}

export interface MySQLIndex {
    name: string
    fields: IndexField[]
    unique?: boolean
    indexType?: string
    errorMessage: string
}

export interface ExecuteContext {
    conn?: EnhancedConnection
}

export interface KvOption {
    key: string,
    value: string
}
export interface FieldMeta {
    system?: boolean
    name: string
    type: string
    required?: boolean
    refEntity?: string
    multiple?: boolean
    label: string
    persistType?: string
    sqlColM?: number
    inputType?: string
    fastSearch?: boolean
    comment?: string
    fileStoreDir?: string
    showInListPage?: boolean
    hideInCreatePage?: boolean
    inEditPage?: string
    kvOptions?: KvOption[]
    textOptions?: string[]
}
export interface EntityMeta {
    system?: boolean
    type?: string
    _version?: number
    name: string
    label: string
    _modifiedOn?: Date
    db: string
    dbName?: string
    idType?: string
    tableName?: string
    noPatchSystemFields?: boolean
    mongoIndexes?: MongoIndex[]
    mysqlIndexes?: MySQLIndex[]
    iconField?: string
    digestConfig?: string
    fieldsForDigest?: string[]
    editEnhanceFunc?: string
    noServiceCache?: boolean
    noCreate?: boolean
    noDelete?: boolean
    noEdit?: boolean
    history?: number
    singleton?: boolean
    fields: { [k: string]: FieldMeta }
}

export interface EntityMetaMap {
    [k: string]: EntityMeta
}

export interface EntityValue {
    [k: string]: any
}

export interface GenericCriteria {
    __type?: string
    relation?: string
    items?: any[]
    field?: string
    operator?: string
    value?: any
    [k: string]: any
}

export type MongoCriteria = any

export type AnyCriteria = GenericCriteria | MongoCriteria

export interface RequestResponse {
    body: any
    response: rp.Response
}
export function pRequest(options: rp.Options) {
    return new Promise<RequestResponse>((resolve, reject) => {
        rp(options, (error, response, body) => {
            if (error) {
                reject(error)
            } else {
                resolve({ body, response })
            }
        })
    })
}
